package com.windy.windyplayer;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;

import java.io.IOException;

/**
 * Created by dingfeng on 2016/9/13.
 */
public class CameraPreview extends AppCompatActivity implements TextureView.SurfaceTextureListener {

    private TextureView mTextureView;
    private SurfaceTexture mSurfaceTexture;
    private Surface mSurface;
    private Camera mCamera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_texture_view);
        mTextureView = (TextureView) findViewById(R.id.textureView);
        mTextureView.setSurfaceTextureListener(this);

        findViewById(R.id.btnRotation).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTextureView.setRotation(45.0f);
            }
        });

        findViewById(R.id.btnAlpha).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTextureView.setAlpha(0.5f);
            }
        });

    }


    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        Log.d("dingfeng", "onSurfaceTextureAvailable...");
        mSurfaceTexture = surface;
        mSurface = new Surface(surface);

        cameraPreview();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
        Log.d("dingfeng", "onSurfaceTextureSizeChanged...");
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        Log.d("dingfeng", "onSurfaceTextureDestroyed...");

        mCamera.stopPreview();
        mCamera.release();

        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        Log.d("dingfeng", "onSurfaceTextureUpdated...");
    }

    private void cameraPreview() {
        mCamera = android.hardware.Camera.open();
        try {
            mCamera.setPreviewTexture(mSurfaceTexture);
            mCamera.startPreview();
            mCamera.setDisplayOrientation(90);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
